import requests
import time
from statistics import mean

def ping_test(url):
    try:
        start_time = time.time()
        requests.get(url, timeout=1)  # 减少超时时间到1秒
        return (time.time() - start_time) * 1000
    except:
        return None

def download_speed_test(url):
    try:
        # 使用 stream=True 和 chunk_size 来优化下载
        start_time = time.time()
        response = requests.get(url, stream=True, timeout=3)
        content_size = 0
        chunk_size = 8192
        
        for chunk in response.iter_content(chunk_size=chunk_size):
            if chunk:
                content_size += len(chunk)
                # 如果已下载超过1MB，就足够计算速度了
                if content_size >= 1024 * 1024:
                    break
        
        download_time = time.time() - start_time
        speed = (content_size * 8) / (download_time * 1_000_000)  # 转换为 Mbps
        return speed
    except:
        return None

def test_speed():
    print("开始测试网络速度，请稍候...")
    
    # 减少测试服务器数量，只用响应最快的几个
    ping_servers = [
        "https://www.baidu.com",
        "https://www.qq.com"
    ]
    
    # 使用较小的文件进行测试
    download_servers = [
        "https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe"  # 只用一个测试服务器
    ]
    
    # 测试延迟
    print("正在测试网络延迟...")
    ping_results = []
    for server in ping_servers:
        result = ping_test(server)
        if result:
            ping_results.append(result)
    
    # 测试下载速度
    print("\n正在测试下载速度...")
    download_speeds = []
    speed = download_speed_test(download_servers[0])
    if speed:
        download_speeds.append(speed)
    
    # 输出结果
    print("\n测试结果:")
    if ping_results:
        print(f"平均网络延迟: {mean(ping_results):.2f} ms")
        print(f"最低延迟: {min(ping_results):.2f} ms")
    else:
        print("网络延迟测试失败")
        
    if download_speeds:
        print(f"下载速度: {mean(download_speeds):.2f} Mbps")
    else:
        print("下载速度测试失败")

if __name__ == "__main__":
    try:
        test_speed()
    except Exception as e:
        print(f"测试过程中出现错误: {str(e)}")